﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using DTO;
using BUS;
using Telerik.Web.UI;

namespace TCV_WEB.Admin.Page
{
    public partial class Categories : System.Web.UI.Page
    {
        string strActivity = "";
        string strProductTypeID = "";
        string strLanguageID = "EN";
        public string Username;
        string sErr = "";
        public static int ContentLength;
        public ArrayList arr_id = new ArrayList();
        // ProductType pro;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UsernameAdmin"] == null)
            {
                Response.Redirect("~/Admin/Login.aspx");
            }
            else
            {
                Username = Session["UsernameAdmin"].ToString();
            }
            if (!Page.IsPostBack)
            {
                // pro = new ProductType(strLanguageID);
                this.Reset();
                this.LoadDataGrid();
                LoadComboBox();
                LoadTreeView();
                loadtree();
                LoadLookup("typ", radcbbType);
                //Session["Sort"] = "ASC";
                //  LoadComboxBox();
                //this.lblManageTypeProduct.Text = CommonTask.GetFormTitle("ManageProductTitle");
            }

            btnSave.Attributes.Add("OnClick", "return validform()");
            btnDelete.Attributes.Add("OnClick", "return Confirm_Delete()");
        }

        private void loadtree()
        {
            CategoriesControl ctr = new CategoriesControl();
            DataTable dt = ctr.GetAll(ref sErr);
            radtree.DataFieldID = "ID";
            radtree.DataFieldParentID = "LinkedID";
            radtree.DataTextField = "NameVN";
            radtree.DataValueField = "ID";
            //     radtree.CheckBoxes = true;

            radtree.DataSource = dt;

            radtree.DataBind();
        }

        private void LoadTreeView()
        {
            //string sErr = "";
            //CategoriesControl cateControl = new CategoriesControl();
            //DataTable dt = cateControl.GetRootsCategories(ref sErr);
            //TreeNode[] treeNodes = GetTreeNodes(dt);
            //tvControl.Nodes.Clear();
            //AddTreeNode(tvControl, treeNodes);
            // tvControl.NO
        }

        private void AddTreeNode(TreeView tvControl, TreeNode[] treeNodes)
        {
            string sErr = "";
            CategoriesControl cateControl = new CategoriesControl();
            for (int i = 0; i < treeNodes.Length; i++)
            {
                DataTable dt = cateControl.get_childs(Convert.ToInt32(treeNodes[i].Value), ref sErr);

                tvControl.Nodes.Add(treeNodes[i]);
                if (dt.Rows.Count > 0)
                {
                    TreeNode[] childNodes = GetTreeNodes(dt);
                    AddTreeNode(treeNodes[i], childNodes);
                }
            }
        }

        private void AddTreeNode(TreeNode tvControl, TreeNode[] treeNodes)
        {
            tvControl.ChildNodes.Clear();
            for (int i = 0; i < treeNodes.Length; i++)
            {
                tvControl.ChildNodes.Add(treeNodes[i]);
            }
        }

        private TreeNode[] GetTreeNodes(DataTable dt)
        {
            TreeNode[] result = new TreeNode[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                result[i] = new TreeNode();
                result[i].Value = dt.Rows[i]["ID"].ToString();
                result[i].Text = dt.Rows[i]["NameVN"].ToString();
                //result[i].Expanded. = false;
            }
            return result;
        }

        private void LoadComboBox()
        {
            DataTable dtb = new DataTable();
            try
            {
                CategoriesControl cateControl = new CategoriesControl();
                dtb = cateControl.GetAll(ref sErr);
                //dgvList.DataBind();
                DataRow row = dtb.NewRow();
                row["NameVN"] = "None";
                row["ID"] = "-1";
                dtb.Rows.InsertAt(row, 0);
                ddlCategoryParent.DataSource = dtb;
                ddlCategoryParent.DataTextField = "NameVN";
                ddlCategoryParent.DataValueField = "ID";
                ddlCategoryParent.DataBind();
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
            finally
            {
                dtb.Dispose();
            }
        }
        private void LoadDataGrid()
        {
            DataTable dtb = new DataTable();
            try
            {
                CategoriesControl cateControl = new CategoriesControl();
                dtb = cateControl.GetAll(ref sErr);
                dgvList.DataSource = dtb;
                //dgvList.DataBind();               
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
            finally
            {
                dtb.Dispose();
            }
        }



        private void LoadData(string strProductID)
        {
            strUploadFolder = "~/" + ConfigurationManager.AppSettings["UploadFolder"].ToString();
            int ID = Convert.ToInt32(strProductID);
            CategoriesControl cateControl = new CategoriesControl();
            CategoriesInfo cate = cateControl.Get(ID, ref sErr);
            txtProductTypeID.Text = cate.ID.ToString();
            this.txtproductType.Text = cate.Name;
            txtNameVN.Text = cate.NameVN;
            this.rblIsViewed.SelectedValue = cate.Status.ToString();
            this.txtRank.Text = cate.Rank.ToString();
            ddlCategoryParent.SelectedValue = cate.LinkedID.ToString();
            txtImage.Text = cate.Image;
            txtDecribes.Text = cate.Decribes;
            this.img.ImageUrl = strUploadFolder + (cate.Image == "" ? "noimages.jpg" : cate.Image);
            if (cate.Type != "")
            {
                int iindex = radcbbType.FindItemIndexByValue(cate.Type);
                radcbbType.Items[iindex].Selected = true;
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            //  pro = new ProductType(strLanguageID);
            if (txtproductType.Text == "")
            {
                lblErr.Text = "Category's name is not NULL";
                return;
            }
            CategoriesControl catectr = new CategoriesControl();
            CategoriesInfo cate = new CategoriesInfo();
            try
            {
                if (this.txtProductTypeID.Text.ToString() != "")
                {
                    strActivity = "Update";
                    cate = catectr.Get(Convert.ToInt32(this.txtProductTypeID.Text), ref sErr);

                }
                else
                {
                    strActivity = "Insert";
                    //pro.ProductTypeID = "";

                }

                cate.Name = this.txtproductType.Text;
                cate.NameVN = txtNameVN.Text;
                cate.Status = Convert.ToInt32(rblIsViewed.Text);
                cate.LinkedID = Convert.ToInt32(ddlCategoryParent.SelectedValue);
                cate.Decribes = txtDecribes.Text;
                cate.Image = txtImage.Text;
                cate.Type = radcbbType.SelectedValue;
                try { cate.Rank = Convert.ToInt32(txtRank.Text); }
                catch
                {
                    cate.Rank = 0;
                }
                CategoriesControl cateControl = new CategoriesControl();
                if (strActivity == "Update")
                {
                    sErr = cateControl.Update_Categories(cate);
                }
                else if (strActivity == "Insert")
                {
                    cateControl.Add_Categories(cate, ref sErr);
                }
                if (sErr == "")
                {
                    lblErr.Text = "Successful";
                    this.Reset();
                }
                else
                {
                    lblErr.Text = sErr;
                }
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message.ToString();
            }
            LoadTreeView();
            dgvList.Rebind();
            LoadComboBox();
            loadtree();
        }

        public void Reset()
        {
            this.txtproductType.Text = "";
            this.lblErr.Text = "";
            this.txtProductTypeID.Text = "";
            this.txtRank.Text = "";
            txtDecribes.Text = "";
            txtNameVN.Text = "";

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            // pro = new ProductType(strLanguageID);
            try
            {
                string strID = "";
                if (dgvList.SelectedItems.Count > 0)
                    for (int i = 0; i < dgvList.SelectedItems.Count; i++)
                    {

                        strID += dgvList.SelectedItems[i].OwnerTableView.DataKeyValues[dgvList.SelectedItems[i].ItemIndex]["ID"].ToString() + ",";

                    }
                else
                    strID = txtProductTypeID.Text;
                CategoriesControl cateControl = new CategoriesControl();
                sErr = cateControl.Delete_Categories(strID);
                dgvList.Rebind();
                LoadTreeView();
                LoadComboBox();
                loadtree();
                this.Reset();
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }

        protected void LoadLookup(String cate, RadComboBox radcbb)
        {
            LookupsControl lkctr = new LookupsControl();
            DataTable dt = lkctr.Get_datatable(cate, ref sErr);

            LookupsInfo inf = new LookupsInfo();


            if (dt.Rows.Count > 0)
            {
                radcbbType.DataTextField = "Description";
                radcbbType.DataValueField = "Code";
                
                radcbb.DataSource = dt;
                //      radcbbPromote.DataBind();
                radcbb.DataBind();

            }
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            this.Reset();
        }

        string strUploadFolder = "";
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            FileUpload fupload = this.fulImage.FindControl("fulImage") as FileUpload;
            HttpPostedFile postFile = fupload.PostedFile;
            strUploadFolder = "~/" + ConfigurationManager.AppSettings["UploadFolder"].ToString();
            ContentLength = Convert.ToInt32(ConfigurationManager.AppSettings["ContentLength"].ToString());
            if (fupload.HasFile == true)
            {
                if (postFile.ContentLength < ContentLength)
                {
                    try
                    {
                        string filename = DateTime.Now.ToFileTimeUtc() + fupload.FileName;
                        string strImagePath = Server.MapPath(strUploadFolder + filename);
                        fupload.SaveAs(strImagePath);
                        this.img.ImageUrl = strUploadFolder + filename;
                        this.txtImage.Text = filename;
                    }
                    catch (Exception ex)
                    {
                        lblErr.Text = ex.Message;
                    }
                }
                else
                {
                    lblErr.Text = "Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
                }

            }
            else
            {

                lblErr.Text = " file đã tồn tại"; //"Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
            }
        }

        protected void tvControl_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {

        }

        protected void tvControl_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode node = tvControl.SelectedNode;
            LoadData(node.Value);

            //if (node.Expanded != null && node.Expanded.Value == false)
            //    node.Collapse();
            //else
            //    node.Expand();
        }

        protected void tvControl_TreeNodeCollapsed(object sender, TreeNodeEventArgs e)
        {

        }

        protected void tvControl_TreeNodeCheckChanged()
        {

        }

        protected void tvControl_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
        {
            CategoriesControl cateControl = new CategoriesControl();
            string sErr = "";
            for (int i = 0; i < e.Node.ChildNodes.Count; i++)
            {
                int ID = Convert.ToInt32(e.Node.ChildNodes[i].Value);
                DataTable dt = cateControl.get_childs(ID, ref sErr);
                if (dt.Rows.Count > 0)
                {
                    TreeNode[] treeNodes = GetTreeNodes(dt);
                    AddTreeNode(e.Node.ChildNodes[i], treeNodes);
                }
            }
        }

        protected void tvControl_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {

        }

        protected void dgvList_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            LoadDataGrid();
        }

        protected void dgvList_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridDataItem && e.Item.DataItem != null)
            {
                try
                {
                    DataRow row = ((DataRowView)e.Item.DataItem).Row;
                }
                catch (Exception ex)
                { }

            }
        }

        protected void dgvList_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName.ToUpper() == "DETAIL")
            {
                strProductTypeID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString().Trim();
                Session["IDCategory"] = strProductTypeID;
                Response.Redirect("~/Admin/Page/Productpage.aspx");
                //Session["ProductID"] = strProductID;
            }
            else if (e.CommandName.ToUpper() == "LOAD")
            {
                strProductTypeID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString().Trim();
                e.Item.Selected = true;
                LoadData(strProductTypeID);
            }
        }

        protected void radtree_NodeCheck(object sender, RadTreeNodeEventArgs e)
        {
            if (e.Node.Checked)
            {
                arr_id.Add(e.Node.Value);
            }
        }

        protected void radtree_Load(object sender, EventArgs e)
        {
            Loadtreebox(radtree.Nodes);
        }

        protected void Loadtreebox(RadTreeNodeCollection radtv)
        {

            foreach (RadTreeNode node in radtv)
            {
                if (node.Nodes.Count > 0)
                    Loadtreebox(node.Nodes);
                if (node.Value == "2" || node.Value == "3" || node.Value == "4")
                    node.Checked = true;
            }
        }

        protected void radtree_NodeCreated(object sender, RadTreeNodeEventArgs e)
        {

        }

        protected void radtree_TemplateNeeded(object sender, RadTreeNodeEventArgs e)
        {

        }

        protected void radtree_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            LoadData(e.Node.Value);
        }

    }
}
